//
//  HMHomeViewController.swift
//  swift微博项目
//
//  Created by huodian on 16/9/22.
//  Copyright © 2016年 huodian. All rights reserved.
//

import UIKit
import SVProgressHUD

let reuserID = "HMHomeTableViewCell"

let retweedID  = "HMRetweetedCell"

class HMHomeViewController: HMBaseViewController{

    
    let refreshView = HMDesignRefreshView()
//    lazy var statues : [HMStatuesModel] = [HMStatuesModel]()
    
    lazy var homeModel : HMHomeModel = HMHomeModel()
    
    
    lazy var activityIndecator : UIActivityIndicatorView = {
       
        let le = UIActivityIndicatorView.init(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)

//        le.startAnimating()
        
        return le
        
        
    }()
    
    lazy var topTipLable:UILabel = {
       
        let l = UILabel(title: "", font: 14, corlor: UIColor.white)
        
        l.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 35)
        
        l.textAlignment = .center
        
        l.backgroundColor = UIColor.orange
        
        l.isHidden = true
        
        return l
        
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
//去掉分割线
        self.tableView.separatorStyle = .none
        
        if !load {
            firstView.loadUnsameview(detail: "呀呀呀呀,德玛西亚,阿拉啦啦啦啦啦啦啦啦啦", imageNamed: nil)
            return
        }
        
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageNamed:"navigationbar_pop",target:self ,action:#selector(clikItem))
    
        
       
        
        
        setTheCellForNib()
        
        
         loadData()
        
      
        
        
        
    }
    
    internal func loadData() {
        
        homeModel.loadThedata(isPulling: activityIndecator.isAnimating, finish: { (success,count1) in
            
            if !success {
                
                SVProgressHUD.showError(withStatus: "封装的时候不要蹦丫")
                
                return
            }
          
            
         //   self.refreshControl?.endRefreshing()
            //数据加载成功将自定义下拉刷新页面状态修改为起始状太
          //  self.refreshView.refreshing = .Normall(用方法替代)
          
            
           
           self.refreshView.stopAnimation()
            
         
            //注意(其后面代码的)执行顺序,以免导致代码无效
            if !self.activityIndecator.isAnimating {
                
               self.setTipLable(count: count1)
                
            }
            
               self.activityIndecator.stopAnimating()
            
            self.tableView.reloadData()
            
        
        })
    
    
    
                
            
            
         
        
        
    }
    
    internal func setTipLable(count:Int){
        if topTipLable.isHidden == false {
            return
        }
        
        topTipLable.text = count == 0 ? "没有新的消息" : "有\(count)条新消息"
        
       print(count)
        
        topTipLable.isHidden = false
        
        UIView.animate(withDuration: 1, animations: { 
            self.topTipLable.frame.origin.y = navBarHeight
            }) { (_) in
                
                UIView.animate(withDuration: 0.5, delay: 1, options: [], animations: { 
                    self.topTipLable.frame.origin.y = navBarHeight - 35
                    }, completion: { (_) in
                        
                        self.topTipLable.isHidden = true
                        
                })
                
        }
        
        
        
        
        
        
    }
    
    func clikItem(){
        
        self.navigationController?.pushViewController(HMTempViewController(), animated: true)
        
    }
    
    func setTheCellForNib()
    {
        
        let nibcell = UINib(nibName:"HMHomeTableViewCell", bundle: nil)
        
        tableView.register(nibcell, forCellReuseIdentifier: reuserID)
        
        let nibretweed = UINib(nibName: "HMRetweetedCell", bundle: nil)
        
        tableView.register(nibretweed, forCellReuseIdentifier: retweedID)
        
       tableView.tableFooterView = activityIndecator
        
        
        //让下拉刷新和加载数据绑定在一起
   //     refreshControl = UIRefreshControl()
    
     //   refreshControl?.addTarget(self, action: #selector(loadData), for: UIControlEvents.valueChanged)
   
        
        
        self.view.addSubview(refreshView)
        
        refreshView.addTarget(self, action: #selector(loadData), for: UIControlEvents.valueChanged)
        
        
        
        self.topTipLable.frame.origin.y = navBarHeight - 35
        
         self.navigationController?.view.addSubview(topTipLable)
        
        self.navigationController?.view.insertSubview(topTipLable, belowSubview: (self.navigationController?.navigationBar)!)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
extension HMHomeViewController{
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return homeModel.homeModelArray.count
        
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = homeModel.homeModelArray[indexPath.row]

        let realeCellID = chooseTheCell(viewModel: model)
        
        
        let cell = tableView.dequeueReusableCell(withIdentifier: realeCellID, for: indexPath) as! HMHomeTableViewCell
        
       
        
        cell.viewModel = model
        
        return cell
        
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        
        if indexPath.row == homeModel.homeModelArray.count - 2 && activityIndecator.isAnimating == false{
            
            
            activityIndecator.startAnimating()
            
            loadData()
            
            
        }
        
        
        
        
    }
    
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let model = homeModel.homeModelArray[indexPath.item]
        
        let realeCellID = chooseTheCell(viewModel: model)
        
        let cell  = getTheCell(cellId: realeCellID)
        
        let rowHeight = cell.rowHeight(viewModel: model)
        
        
        
        
        
        
        
        return rowHeight
    }
    
    
    
    func getTheCell(cellId:String)->HMHomeTableViewCell{
        
        let realCell = cellId == retweedID ? retweedID :reuserID
        
        return UINib(nibName: realCell, bundle: nil).instantiate(withOwner: nil, options: nil).last as! HMHomeTableViewCell
        
        
        
        
    }
    
    func chooseTheCell(viewModel:HMStatuesCellModel) -> String {
        
        if viewModel.statues?.retweeted_status == nil {
            
            return reuserID
            
        }
        return retweedID
        
        
    }
    
    
}
